package com.lidx.back.statistics.controller.admin;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.lidx.back.statistics.entity.Role;
import com.lidx.back.statistics.entity.SysUser;
import com.lidx.back.statistics.service.ISysUserService;

@Controller
@RequestMapping(value="/admin/user")
public class SysUserController {

	@Autowired
	private ISysUserService userService;
	
	@RequestMapping(value="add",method=RequestMethod.GET)
	public String add(Model model){
		SysUser user = new SysUser();
		model.addAttribute("user", user);
		model.addAttribute("allRoles", userService.getUserRoles());
		return "sysUser/add";
	}
	
	@RequiresRoles(value = { "1" })
	@RequestMapping(value="add",method=RequestMethod.POST)
	public String addGo(SysUser user,Model model,RedirectAttributes redirectAttributes){
		/* Subject currentUser = SecurityUtils.getSubject();
		    if (!currentUser.hasRole("1")) {
		        throw new AuthorizationException("只有公司管理员才能添加用户");
	    }*/
		
		String loginName = user.getLoginName();
		if(StringUtils.isNotBlank(loginName)){
			SysUser userDB = userService.getUserByLoginName(loginName);
			if(userDB != null){
				model.addAttribute("msg", "此用户名已经存在，请选择其他登录名进行添加~");
				return add(model);
			}
		}
		
		// 角色数据有效性验证，过滤不在授权内的角色
		List<Role> roleList = Lists.newArrayList();
		List<Integer> roleIdList = user.getRoleIdList();
		for (Role r : userService.getUserRoles()) {
			if (roleIdList.contains(r.getId())) {
				roleList.add(r);
			}
		}
		user.setRoleList(roleList);
		userService.saveSysUser(user);
		return "redirect:/admin/user/list";
	}
	@RequiresRoles(value = { "1" })
	@RequestMapping(value="list",method=RequestMethod.GET)
	public String userList(Model model){
		model.addAttribute("userList", userService.getUserList());
		return "sysUser/list";
	}
	
	/**
	 * 添加Flash消息
     * @param messages 消息
	 */
	protected void addMessage(RedirectAttributes redirectAttributes, String... messages) {
		StringBuilder sb = new StringBuilder();
		for (String message : messages){
			sb.append(message).append(messages.length>1?"<br/>":"");
		}
		redirectAttributes.addFlashAttribute("message", sb.toString());
	}
}
